<!-- src/components/XtxGuess.-fvue -->
<script setup lang="ts">
import { getHomeGoodsApi } from '@/api/home.ts'
import type { HomeGuess } from '@/types/home'
import { ref } from 'vue'
import type { PageParams } from '@/types/global'

// Required<PageParams> 把 pageParams 对象中的可选属性变为必选，
// 因为在当前页面中这两个请求参数是肯定会传的
const pageParams: Required<PageParams> = {
  page: 1,
  pageSize: 10,
}
const guessList = ref<HomeGuess[]>([])
const finish = ref(false)
const isLoading = ref(false) // 🔐 锁变量
// 获取猜你喜欢数据
const getHomeGoods = async () => {
  if (isLoading.value) return // 1️⃣ 检查锁状态
  isLoading.value = true // 2️⃣ 加锁

  try {
    // 3️⃣ finish = true 代表没有更多数据，停止加载
    if (finish.value) {
      return uni.showToast({ icon: 'none', title: '没有更多数据~' })
    }
    // 4️⃣ 异步操作
    const res = await getHomeGoodsApi(pageParams)
    guessList.value.push(...res.result.items)

    // 当前页请求完，判断是否有下一页，有的话 page++，否则 finish = true
    if (pageParams.page >= res.result.pages) finish.value = true
    else pageParams.page++
  } finally {
    isLoading.value = false // 5️⃣ 释放锁（确保异常时也能解锁）
  }
}
getHomeGoods()

const resetHomeGoods = () => {
  guessList.value = []
  finish.value = false
  pageParams.page = 1
}

defineExpose({
  getHomeGoods,
  resetHomeGoods,
})
</script>

<template>
  <!-- 猜你喜欢 -->
  <view class="caption">
    <text class="text">猜你喜欢</text>
  </view>
  <view class="guess">
    <navigator
      class="guess-item"
      v-for="item in guessList"
      :key="item.id"
      :url="`/pages/goods/goods?id=${item.id}`"
    >
      <!-- #ifdef MP-WEIXIN -->
      <image class="image" :src="item.picture" lazy-load></image>
      <!-- #endif -->
      <!-- #ifdef APP-PLUS || H5 -->
      <img class="image" :src="item.picture" loading="lazy" alt="" />
      <!-- #endif -->
      <view class="name ellipsis">{{ item.name }}</view>
      <view class="price">
        <text class="small">¥</text>
        <text>{{ item.price }}</text>
      </view>
    </navigator>
  </view>
  <view class="loading-text">{{ finish ? '没有更多数据~' : '正在加载...' }}</view>
</template>

<style lang="scss">
@import 'style/XtxGuess';
</style>
